#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#define PORT 9876

int client_sockfd;
int connected;

void *thread0(void *param)
{
	char fromClient[BUFSIZ];
	while (read(client_sockfd, fromClient, sizeof(fromClient)) != 0)
	{
		printf("\nFrom Client: %s\n", fromClient);
		memset(fromClient, 0, BUFSIZ);
	}
	connected = 0;
	close(client_sockfd);
	return param;
}

int main (int argc, char* argv[])
{
	char toClient[BUFSIZ];
	struct sockaddr_in serv_addr, client_addr;
	int sockfd, len;
	pthread_t thread;
	connected = 0;
	
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
		exit(2);

	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(PORT);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
	listen(sockfd, 3);

	for (;;)
	{
		len = sizeof(client_addr);
		client_sockfd = accept(sockfd, (struct sockaddr *) &client_addr, (socklen_t *) &len);
		connected = 1;
		pthread_create(&thread, NULL, thread0, 0);

		while (connected)
		{
			fgets(toClient, sizeof(toClient), stdin);
			write(client_sockfd, toClient, strlen(toClient));
			printf("To Client: %s\n", toClient);
		}
	}
}

